﻿using System.Collections.Generic;
using System.Text;
using Core.Domain;
using Core.Domain.Lexems;

namespace Core.SyntaxAnalysis.Classes
{
    /// <summary> присваивание </summary>
    public class Assign : Stmt
    {
        public readonly Lexem Left;
        public readonly Lexem Lex;
        public readonly Expr Right;

        public Assign(Lexem left, Expr right, Lexem lex)
        {
            Left = left;
            Right = right;
            Lex = lex;
        }

        public DataType GetTypeOfLeftSide()
        {
            Identificator id = Env.FindId(Left);
            if (id == null)
            {
                return null;
            }
            return id.GetExprType();
        }

        public override bool StmtSemanticCheck(ref List<CompilerError> errors)
        {
            bool error = false;
            Identificator id = Env.FindId(Left);
            if (id == null)
            {
                errors.Add(new CompilerError(errors.Count + 1, Resources.VariableWasNotDefinedErrorMessage, Left));
                error = true;
            }
            else
            {
                DataType typeLeft = id.GetExprType();
                DataType typeRight = Right.GetExprType();
                if (typeRight.TypeId() < 0 || typeRight.TypeId() != typeLeft.TypeId())
                {
                    errors.Add(new CompilerError(errors.Count + 1, Resources.LeftAndWriteTypesOfAssignDoNotMatch, Lex));
                    error = true;
                }
            }
            return !error;
        }

        public override void StmtGenerate(StringBuilder s)
        {
            string r = Right.Generate(s);
            s.AppendLine(Left.StrValue + " = " + r);
        }
    }
}